<template>
  <view class="container">
    <view class="contract-content">
      <!-- 合同类型 -->
      <ve-card>
        <ve-cell class="contract-type" label="合同类型" :borderBottom="false">
          <ve-radio v-model="contractType" :list="radioList" @confirm="onChangeContract" />
        </ve-cell>
      </ve-card>
      <view class="info-tip">将会根据以下信息生成电子合同，如需修改，请先前往订单修改页面进行调整后再生成。</view>
      <!-- 客户信息 -->
      <ve-card title="客户信息">
        <template v-if="infoDetail.memberType == 2">
          <ve-cell label="客户类型">{{ infoDetail.memberTypeName || '-' }}</ve-cell>
          <ve-cell label="承租人">{{ infoDetail.memberName || '-' }}</ve-cell>
          <ve-cell label="联系电话" v-if="contractPayType !== 0 && contractPayType !== 3">{{ infoDetail.memberPhone || '-' }}</ve-cell>
          <ve-cell label="证件类型">{{ infoDetail.cardTypeName || '-' }}</ve-cell>
          <ve-cell label="证件号">{{ infoDetail.cardNumber || '-' }}</ve-cell>
          <ve-cell label="紧急联系人">{{ infoDetail.emergencyContactName || '-' }}</ve-cell>
          <ve-cell label="紧急联系人手机号">{{ infoDetail.emergencyContactPhone || '-' }}</ve-cell>
        </template>
        <template v-else>
          <ve-cell label="客户类型">{{ infoDetail.memberTypeName || '-' }}</ve-cell>
          <ve-cell label="客户公司名称">{{ infoDetail.clientName || '-' }}</ve-cell>
          <ve-cell label="承租人">{{ infoDetail.memberName || '-' }}</ve-cell>
          <ve-cell label="证件类型">{{ infoDetail.cardTypeName || '-' }}</ve-cell>
          <ve-cell label="证件号">{{ infoDetail.cardNumber || '-' }}</ve-cell>
          <ve-cell label="紧急联系人">{{ infoDetail.emergencyContactName || '-' }}</ve-cell>
          <ve-cell label="紧急联系人手机号">{{ infoDetail.emergencyContactPhone || '-' }}</ve-cell>
        </template>
      </ve-card>
      <!-- 租赁信息 -->
      <ve-card title="租赁信息">
        <ve-cell :label="contractType == 2 ? '预计续租周期' : '预计租赁周期'">
          <view>
            <view>{{ infoDetail.startTime }}至</view>
            <view>{{ infoDetail.endTime || '-' }}</view>
            <view class="rent-days">租期：{{ infoDetail.rentDays || '-' }}</view>
          </view>
        </ve-cell>
        <view v-if="contractType == 2" class="info-tip relet-tip">
          续租周期取的是当前订单最新的租赁周期，如需修改，请通过修改合同的功能进行调整
        </view>
        <ve-cell label="取车门店">
          <view>
            <view>{{ infoDetail.siteName || '-' }}</view>
            <view class="shop-text">
              <image v-if="infoDetail.sendServiceFlag" src="@/static/images/checkbox-checked.png" mode="widthFix"></image>
              <image v-else src="@/static/images/checkbox-nochecked.png" mode="widthFix"></image>
              <text>上门送车</text>
            </view>
          </view>
        </ve-cell>
        <ve-cell label="上门送车地址">{{ infoDetail.address || '-' }}</ve-cell>
        <ve-cell label="还车门店">
          <view>
            <view>{{ infoDetail.returnSiteName || '-' }}</view>
            <view class="shop-text">
              <image v-if="infoDetail.returnServiceFlag" src="@/static/images/checkbox-checked.png" mode="widthFix"></image>
              <image v-else src="@/static/images/checkbox-nochecked.png" mode="widthFix"></image>
              <text>上门取车</text>
            </view>
          </view>
        </ve-cell>
        <ve-cell label="上门取车地址">{{ infoDetail.returnAddress || '-' }}</ve-cell>
      </ve-card>
      <!-- 车辆信息 -->
      <ve-card title="车辆信息">
        <ve-cell label="车辆来源">
          {{ infoDetail.carSourceName || '-' }}
        </ve-cell>
        <ve-cell label="车牌号">
          {{ infoDetail.carLicenseNo || '-' }}
        </ve-cell>
        <ve-cell label="排车车型">
          {{ infoDetail.carModelName || '-' }}
        </ve-cell>
        <ve-cell label="交车里程" v-if="infoDetail.isExistenceStartCarMileageFlag">
          <ve-input-number :precision="0" v-model="infoDetail.startCarMileageContract" />
        </ve-cell>
        <ve-cell label="交车油(电)量" v-if="infoDetail.isExistenceStartCarOilFlag">
          <ve-input  v-model="infoDetail.startCarOilContract" :maxlength="20" />
        </ve-cell>
      </ve-card>
      <!-- 费用信息 -->
      <view v-if="contractPayType == 0 || contractPayType == 3">
        <ve-card title="费用信息" v-if="infoDetail.contractFee && infoDetail.contractFee.length > 0">
          <ve-cell-price :label="`${item.name}`" :value="Math.abs(item.value)" v-for="(item, index) in infoDetail.contractFee" :key="index">
          </ve-cell-price>
        </ve-card>
      </view>
      <ve-card title="费用信息" v-else>
        <ve-cell-price label="租车费" :value="Math.abs(infoDetail.totalAmount)"> </ve-cell-price>
        <ve-cell-price label="租车押金" :value="Math.abs(infoDetail.carDeposit)"> </ve-cell-price>
        <ve-cell-price label="违章押金" :value="Math.abs(infoDetail.illegalDeposit)"> </ve-cell-price>
      </ve-card>
    </view>
    <!-- 底部 footer -->
    <ve-bottom-box>
      <ve-button size="long" :loading="okLoading" type="primary" @click="submitFn">确认</ve-button>
    </ve-bottom-box>
    <ve-modal
      :showCancel="false"
      title="提示"
      okText="我已知晓"
      v-model="errModalContent.visible"
      @confirm="errModalContent.visible = false"
    >
      <view>请先前往PC端后台-增值服务>电子合同>合同模板模块</view>
      <view class="modal-content">
        请先上传{{ errModalContent.templateName }}{{ errModalContent.templateTypeName }}模板的
        <text style="color: red">公司印章</text>，再生成电子合同
      </view>
    </ve-modal>
  </view>
</template>

<script setup>
  import { ref, provide, computed, nextTick, h, reactive } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { getShortContractOrderDetail, createQysContract } from '@/api/order/sOrder'
  import { getLongContractOrderDetail } from '@/api/order/lOrder'
  import { getContractDataAPI } from '@/api/order/contract'
  import { numFormatThousands } from '@/vehicle-ui/utils/tools.js'

  // 合同支付类型
  const contractPayType = ref()
  // 订单编号
  const orderCode = ref()

  const radioList = computed(() => {
    let list = [
      {
        label: '租车合同',
        value: 1,
      },
    ]
    if (contractPayType.value == 0 || contractPayType.value == 3) {
      list.push({
        label: '续租合同',
        value: 2,
      })
    }
    return list
  })

  const onChangeContract = ({ value }) => {
    contractType.value = value
    getContractDetail(id_value.value)
  }

  // 表单对象
  const infoDetail = ref({})
  const contractType = ref(1)
  // 订单类型 1、短租 2、长租
  const orderType = ref(1)
  // 合同记录ID
  const contractId = ref(null)
  const id_value = ref()
  const errModalContent = reactive({
    visible: false,
    templateName: '',
    templateTypeName: '',
  })

  const okLoading = ref(false)
  const submitFn = () => {
    okLoading.value = true
    let params = {
      orderType: orderType.value,
      orderCode: infoDetail.value.orderCode || orderCode.value,
      contractType: contractType.value, //合同类型 1:租车合同 2：续租合同 3:换车合同 默认1
      id: contractId.value, //合同记录ID（重新生成时传）
      operationType: contractId.value ? 1 : 0, //操作方式  0 手动生成 1重新生成
      payType: contractPayType.value == 0 || contractPayType.value == 3 ? 0 : 1, // 付费版免费版类型
      contractFee: infoDetail.value.contractFee, // 费用集合
      startCarMileageContract: infoDetail.value.isExistenceStartCarMileageFlag ? infoDetail.value.startCarMileageContract : null,
      startCarOilContract: infoDetail.value.isExistenceStartCarOilFlag ? infoDetail.value.startCarOilContract : null,
    }

    createQysContract(params)
      .then((res) => {
        if (res.result?.createErrorCode == 1001) {
          uni.showModal({
            title: '合同生成失败',
            content: '请将承租人姓名修改为上次已通过实名认证的姓名，再进行重新生成合同的操作。',
            cancelText: '关闭',
            confirmText: '前往修改',
            success: function (res) {
              if (res.confirm) {
                orderType.value == 1
                  ? uni.navigateTo({
                      url: `/pages/order/short-order/form/edit?id=${infoDetail.value.id}`,
                    })
                  : uni.navigateTo({
                      url: `/pages/order/long-order/form/edit?id=${infoDetail.value.id}`,
                    })
              }
            },
          })
        } else if (res.result?.resultErrorCode == 9999) {
          Object.assign(errModalContent, {
            visible: true,
            templateName: res.result.templateName,
            templateTypeName: res.result.templateTypeName,
          })
        } else if (res.result?.resultErrorCode !== 9999 && res.result?.createErrorCode == null) {
          uni.showToast({
            title: '生成合同成功',
            icon: 'none',
          })
          uni.$emit('refreshNumData')
          uni.navigateBack()
        }
        okLoading.value = false
      })
      .catch(() => {
        okLoading.value = false
      })
  }
  // 详情
  const getContractDetail = (id) => {
    // 付费版免费版类型(参考submitFn)
    if (contractPayType.value == 0 || contractPayType.value == 3) {
      // 免费版合同
      getContractDataAPI({
        id: contractId.value,
        orderId: id,
        orderType: orderType.value,
        contractType: contractType.value,
      }).then((res) => {
        infoDetail.value = res.result
      })
    } else {
      // 收费版合同
      if (orderType.value == 1) {
        // 短租
        getShortContractOrderDetail({
          id: id,
        }).then((res) => {
          const { memberInfoDto } = res.result
          infoDetail.value = {
            ...res.result.orderInfo,
            emergencyContactName: memberInfoDto.emergencyContactName,
            emergencyContactPhone: memberInfoDto.emergencyContactPhone,
          }
        })
      } else {
        // 长租
        getLongContractOrderDetail({
          id: id,
        }).then((res) => {
          const { memberInfoDto } = res.result
          infoDetail.value = {
            ...res.result.orderInfo,
            carLicenseNo: res.result.orderInfo.licenseNo,
            orderCode: res.result.orderInfo.orderNo,
            startTime: res.result.orderInfo.expectedUseCarTime,
            endTime: res.result.orderInfo.expectedReturnCarTime,
            rentDays: res.result.orderInfo.leaseNumberStr,
            carModelName: res.result.orderInfo.modelName,
            totalAmount: res.result.orderInfo.carRentAmount,
            carDeposit: res.result.orderInfo.carDepositAmount,
            illegalDeposit: res.result.orderInfo.violationDepositAmount,
            orderStatus: res.result.orderInfo.status,
            emergencyContactName: memberInfoDto.emergencyContactName,
            emergencyContactPhone: memberInfoDto.emergencyContactPhone,
          }
        })
      }
    }
  }
  onLoad((options) => {
    id_value.value = options.id
    orderType.value = options.orderType == 2 ? 1 : 2
    contractId.value = options.contractId || null
    contractPayType.value = options.contractPayType
    orderCode.value = options.orderCode
    if (id_value.value) {
      getContractDetail(id_value.value)
    }
  })
</script>
<style lang="less" scoped>
  .container {
    display: flex;
    flex-direction: column;
    .contract-content {
      padding: 24rpx;
      padding-bottom: 125rpx;
    }
    .radio {
      display: flex;
      align-items: center;
    }
    .contract-type {
      :deep(.ve-cell-content) {
        justify-content: flex-end !important;
      }
    }
  }
  .info-tip {
    background: #e8f3ff;
    font-size: 28rpx;
    line-height: 44rpx;
    padding: 18rpx 32rpx;
    color: #1d2129;
    margin-bottom: 24rpx;
  }
  .relet-tip {
    background: #fff7e8;
  }
  .rent-days {
    font-size: 30rpx;
    text-align: left;
    color: #3072f6;
  }
  .modal-content {
    padding-bottom: 20rpx;
  }
  #footer-box {
    position: fixed;
    bottom: 0;
    width: 100%;
    // height: 120rpx;
    background-color: #ffffff;
    z-index: 100;
    /deep/ .ve-button {
      padding: 0;
    }
  }
  .shop-text {
    image {
      width: 28rpx;
      height: 28rpx;
      margin-right: 10rpx;
    }
    text {
      color: #c9cdd4;
    }
  }
  .ve-checkbox {
    display: flex;
    align-items: center;
    margin-right: 32rpx;
    .ve-checkbox__label {
      font-size: 28rpx;
      font-weight: 400;
      color: #1d2129;
      margin-left: 16rpx;
    }
  }
  .ve-checkbox__icon-wrap {
    .checkbox__icon-wrap__icon {
      font-size: 38rpx;
    }
  }
  /deep/ .uni-input-input {
    text-align: left;
  }
  /deep/ .uni-input-placeholder {
    text-align: left;
  }
</style>
